package com.dosen.api.third.party.register.config;

import com.alibaba.fastjson.JSON;
import com.dosen.api.common.enums.ResponseEnum;
import com.dosen.api.third.party.register.model.feign.FeignResponseDTO;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.nio.charset.Charset;


/**
 * @version V1.0
 * @author: guangcheng
 * @date: 2022/8/22 11:10
 * @description:
 */
@Component
public class ThirdPartyFeignDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        FeignResponseDTO dto = new FeignResponseDTO().setCode(response.status() + "").setMessage(ResponseEnum.FEIGN_API_ERROR.getMessage());
        if (response.status() != HttpStatus.OK.value()) {
            try {
                dto.setStatus(response.status());
                if (ObjectUtils.isEmpty(response.body())) {
                    dto.setMessage(response.reason());
                    return new RuntimeException(JSON.toJSONString(dto));
                } else {
                    // 原始的返回内容
                    String json = Util.toString(response.body().asReader(Charset.defaultCharset()));
                    return new RuntimeException(json);
                }
            } catch (IOException e) {
                return new RuntimeException(JSON.toJSONString(dto));
            }
        }
        return new RuntimeException(JSON.toJSONString(dto));
    }
}
